package com.zhonghui.scm.service.impl;

import com.zhonghui.scm.domain.ScmSalePlan;
import com.zhonghui.scm.domain.ScmSalePlanItem;
import com.zhonghui.scm.mapper.ScmSalePlanMapper;
import com.zhonghui.scm.service.IScmSalePlanService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

/**
 * 销售计划Service业务层处理
 * 
 * @author zhonghui
 * @date 2022-05-26
 */
@Service
public class ScmSalePlanServiceImpl implements IScmSalePlanService
{
    @Autowired
    private ScmSalePlanMapper scmSalePlanMapper;

    /**
     * 查询销售计划
     * 
     * @param id 销售计划主键
     * @return 销售计划
     */
    @Override
    public ScmSalePlan getById(Long id)
    {
        return scmSalePlanMapper.getById(id);
    }

    /**
     * 查询销售计划列表
     * 
     * @param scmSalePlan 销售计划
     * @return 销售计划
     */
    @Override
    public List<ScmSalePlan> getList(ScmSalePlan scmSalePlan)
    {
        return scmSalePlanMapper.getList(scmSalePlan);
    }

    /**
     * 新增销售计划
     * 
     * @param scmSalePlan 销售计划
     * @return 结果
     */
    @Override
    public int add(ScmSalePlan scmSalePlan)
    {
        scmSalePlan.setScheduleNumber(generateNumber("XSJH"));
        int row = scmSalePlanMapper.add(scmSalePlan);
        insertItem(scmSalePlan);
        return row;
    }

    /**
     * 修改销售计划
     * 
     * @param scmSalePlan 销售计划
     * @return 结果
     */
    @Override
    public int edit(ScmSalePlan scmSalePlan)
    {
        scmSalePlanMapper.delItem(scmSalePlan.getId());
        insertItem(scmSalePlan);
        return scmSalePlanMapper.edit(scmSalePlan);
    }

    /**
     * 批量删除销售计划
     * 
     * @param ids 需要删除的销售计划主键
     * @return 结果
     */
    @Override
    public int del(Long[] ids)
    {
        for (Long id : ids) {
            scmSalePlanMapper.delItem(id);
        }
        return scmSalePlanMapper.del(ids);
    }


    public void insertItem(ScmSalePlan scmSalePlan){
        List<ScmSalePlanItem> scmSalePlanItemList = scmSalePlan.getScmSalePlanItemList();

        if (!scmSalePlanItemList.isEmpty()){

        for (ScmSalePlanItem scmSalePlanItem : scmSalePlanItemList) {
            scmSalePlanItem.setScheduleId(scmSalePlan.getId());
        }
        scmSalePlanMapper.addItem(scmSalePlanItemList);

        }
    }

    public String generateNumber(String number){
        Date date = new Date();
        SimpleDateFormat format = new SimpleDateFormat("yyyyMMddHHmmssSSS");
        return number+format.format(date);
    }
}
